<template>
  <div class="role-wrap">
    <continer :showPage="showPage" :isNoTabs="true">
      <template slot="search">
        <QuickSearch :advForm="quickSearchForm" @QuickSearch="queryRoleList"></QuickSearch>
      </template>
      <template slot="oprate">
        <el-button type="primary" size="mini" @click="queryRoleList">查询</el-button>
        <el-button size="mini" @click="addBtnFun" v-functions="['role_management_insert']">新增</el-button>
      </template>
      <template slot="content">
        <instiutionTable
                ref="tableRef"
                @currentChange="currentChangeFun"
                @sizeChange="sizeChange"
                @batchClick="batchClick"
                :batchOperate="batchOperate"
                :pages="roleTablePages"
                :instiutionTableData="roleTableData"
                :instiutionTableHeader="roleTableHeader">
        </instiutionTable>
      </template>
      <template slot="page">
        <addOrEditRole :type="addOrEdit" class="roleContent" :titleArr="titleArr" ref="roleForm" :licenceList="licenceList" @cancelFun="pageBack" @saveRoleFun="saveRoleFun"  @pageBack="pageBack"></addOrEditRole>
      </template>
    </continer>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import { CommonModule } from '@/store/modules/common'
import { deepClone } from '@/utils/common'
import { checkPermission } from '@/utils/directive'
import { organizationConfigModule } from '@/store/modules/config/organizationConfig/index'
import breadcrumb from '@/components/breadcrumb/breadcrumb.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import addOrEditRole from '@/views/config/role/addOrEditRole.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
@Component({
  name: 'role',
  components: {
    breadcrumb,
    instiutionTable,
    addOrEditRole,
    QuickSearch,
    continer
  }
})
export default class Role extends Vue {
  @Ref() private readonly roleForm!: addOrEditRole
  @Ref() private readonly tableRef !: instiutionTable
  [x: string]: any
  private titleArr: any[] = []

  private batchOperate = [ // 批量操作设置
    { name: '批量删除', action: 'batchDelAgentFun', _id: 'role_management_batch_delete' }
  ]

  private showPage: boolean = false

  private roleTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 100
  }

  private quickSearchForm: any = {}

  private addOrEdit = 'add'

  private roleTableHeader: any[] = [ // 表头
    { type: 'select' },
    { label: '角色名称', prop: 'name' },
    { label: '描述', prop: 'description' },
    { label: '使用版本', prop: 'licenceName' },
    { label: '创建人', prop: 'createName' },
    { label: '最后更新时间', prop: 'updateTime', isSort: true }
  ]

  private roleTableData = []

  private licenceList: any = []

  private saveRoleFun (type) {
    this.showPage = false
    this.queryRoleList(type)
  }

  private pageBack () {
    this.showPage = false
  }

  private batchClick (action, selectList) {
    this[action](selectList)
  }

  private batchDelAgentFun (selectedArr: any) { // 批量删除
    this.$confirm('确定要批量删除座席吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let sendData = {}
      if (typeof selectedArr === 'object') { // 单个操作，传ids
        sendData = { ids: selectedArr || [] }
      } else { // 全选传查询条件
        sendData = { condition: { page: this.roleTablePages.current, limit: this.roleTablePages.pageSize, ...this.quickSearchForm.form } }
      }
      const actionData = { url: '/base/action/role/batch/delete', method: 'POST', data: sendData }
      organizationConfigModule.organizationCommonAction(actionData).then(res => {
        if (res) {
          this.$message.success('批量删除角色成功')
          this.tableRef.cancelSelectFun() // 关闭批量操作栏
          this.queryRoleList()
        }
      })
    })
  }

  private handleEdit (row: any) {
    this.addOrEdit = 'edit'
    const actionData = { url: '/base/action/role/get/' + row._id, method: 'GET', data: {} }
    organizationConfigModule.organizationCommonAction(actionData).then(res => {
      if (res) {
        this.titleArr = ['角色管理', '编辑角色']
        this.showPage = true
        this.$nextTick(() => {
          this.roleForm.setRoleData(res)
        })
      }
    })
  }

  private handleDel (row: any) {
    this.$confirm('确定要删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const actionData = { url: '/base/action/role/delete', method: 'POST', data: { _id: row._id } }
      organizationConfigModule.organizationCommonAction(actionData).then(res => {
        this.$message.success('删除角色成功')
        this.queryRoleList()
        this.$deleteCache('roleList', '_id', row._id, true)
      })
    })
  }

  private sizeChange (size: number) {
    this.roleTablePages.pageSize = size
    this.queryRoleList()
  }

  private currentChangeFun (page: number) { // 翻页
    this.roleTablePages.current = page
    this.queryRoleList()
  }

  private queryRoleList (addSuccess?: any) {
    if (addSuccess) { // 新增回到第一页
      this.roleTablePages.current = 1
    }
    const sendData = { page: this.roleTablePages.current, limit: this.roleTablePages.pageSize, ...this.quickSearchForm.form }
    const actionData = { url: '/base/action/role/query', method: 'POST', data: { ...sendData } }
    organizationConfigModule.organizationCommonAction(actionData).then(res => {
      if (res.list) {
        const list = res.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.roleTablePages.pageSize)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.roleTablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.roleTablePages.current = page
            this.queryRoleList()
            return false
          }
        }
        if (list.length > 0) {
          list.forEach((item: any) => {
            const agentObj = deepClone(CommonModule.publicCache.userListObj)[item.createUser]
            const licenceListInfo = this.licenceList.find((licenceItem: any) => licenceItem.licenceId === item.version)
            // const licenceListInfo: any = this.$store.state.common.publicCache.licenceListObj[item.version]
            item.createName = agentObj ? agentObj.name : '--'
            item.licenceName = (licenceListInfo && licenceListInfo.name) || '--'
          })
        }
        this.roleTableData = res.list
        this.roleTablePages.total = res.count
      }
    })
  }

  private addBtnFun () {
    this.addOrEdit = 'add'
    this.showPage = true
    this.titleArr = ['角色管理', '添加角色']
  }

  private mounted () {
    this.$getCache('/base/action/general/cache/query', ['licenceList', 'roleList'], true).then((data: any) => {
      this.licenceList = deepClone(CommonModule.publicCache.licenceList)
      this.quickSearchForm = {
        form: {
          name: '',
          versions: []
        },
        advSearchOptions: [
          { label: '角色名称', inputType: 'input', placeholder: '请输入角色名称', name: 'name' },
          { label: '版本', inputType: 'ele-select', selectData: this.licenceList, multiple: true, name: 'versions', defaultProp: { label: 'name', value: 'licenceId' } }
        ]
      }
      this.$nextTick(() => {
        this.queryRoleList()
      })
    })
  }

  private beforeMount () {
    const handlers: any[] = []
    if (checkPermission(null, { value: ['role_management_edit'] })) {
      handlers.push({ name: '编辑', handleFn: (scope: any) => this.handleEdit(scope.row) })
    }
    if (checkPermission(null, { value: ['role_management_delete'] })) {
      handlers.push({ className: 'danger', name: '删除', handleFn: (scope: any) => this.handleDel(scope.row) })
    }
    this.batchOperate = this.batchOperate.filter(item => checkPermission(null, { value: [item._id] })) // 过滤批量操作的权限
    this.roleTableHeader.push({ label: '操作', width: 100, handlers })
  }
}
</script>

<style lang="stylus" scoped>
  .role-wrap
    width 100%
    height 100%
    position relative
</style>
